package com.bookstore.back.service.impl;

import com.bookstore.back.mapper.UserLogMapper;
import com.bookstore.back.service.UserLogService;
import com.bookstore.back.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户日志服务实现类
 * 
 * @author 程序猿_Ti
 * @since 2025-07-22
 */
@Slf4j
@Service
public class UserLogServiceImpl implements UserLogService {

    @Autowired
    private UserLogMapper userLogMapper;

    @Override
    public void recordLoginLog(Long userId, String ipAddress, String userAgent) {
        try {
            userLogMapper.insertLoginLog(userId, ipAddress, userAgent);
            log.info("记录用户登录日志成功，用户ID：{}，IP：{}", userId, ipAddress);
        } catch (Exception e) {
            log.error("记录用户登录日志失败，用户ID：{}，错误：{}", userId, e.getMessage());
        }
    }

    @Override
    public void recordOperationLog(Long userId, String ipAddress, String userAgent, String operation) {
        try {
            // 构建操作详情JSON
            String details = String.format("{\"operation\":\"%s\",\"timestamp\":\"%s\"}", 
                operation, System.currentTimeMillis());
            
            userLogMapper.insertOperationLog(userId, ipAddress, userAgent, details);
            log.info("记录用户操作日志成功，用户ID：{}，操作：{}，IP：{}", userId, operation, ipAddress);
        } catch (Exception e) {
            log.error("记录用户操作日志失败，用户ID：{}，操作：{}，错误：{}", userId, operation, e.getMessage());
        }
    }

    @Override
    public void recordOperationLog(Long userId, String operation) {
        try {
            // 获取当前请求的HttpServletRequest
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String ipAddress = "unknown";
            String userAgent = "unknown";
            
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                ipAddress = RequestUtil.getClientIpAddress(request);
                userAgent = RequestUtil.getUserAgent(request);
            }
            
            recordOperationLog(userId, ipAddress, userAgent, operation);
        } catch (Exception e) {
            log.error("记录用户操作日志失败，用户ID：{}，操作：{}，错误：{}", userId, operation, e.getMessage());
        }
    }
}
